﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xpedite.Resources.Definitions;
using Xpedite.Localization;

/* Copyright (c) 2010 CBaxter
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), 
 * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 
 * IN THE SOFTWARE. 
 */

namespace Xpedite.Resources.Combiners
{
  internal class TextCombiner : ICombiner
  {
    private static readonly Dictionary<Encoding, Int32> _rankedEncodings = new Dictionary<Encoding, Int32>
    {
      { Encoding.Default, 1},
      { Encoding.UTF7, 2},
      { Encoding.UTF8, 3},
      { Encoding.Unicode, 4},
      { Encoding.UTF32, 5}
    };

    public IResourceContainer Combine(IResourceUrl virtualUrl, IResourceDefinition definition)
    {
      return new ResourceContainer(
        definition.ResourceType,
        virtualUrl, 
        () =>
        {
          IEnumerable<IResource> resources = definition.Resources.Select(item => item.Resource);
          Encoding encoding = GetCompositeResourceEncoding(resources);
          Byte[] newlineBytes = encoding.GetBytes(Environment.NewLine);
          DateTime lastWriteTime = DateTime.UtcNow.Date;
          List<Byte[]> segments = new List<Byte[]>();

          foreach (var resource in resources)
          {
            if (!resource.Compressable)
              throw new XpediteException(String.Format(ExceptionMessages.UncompressibleResourceFound, definition.ReferenceName));

            if (definition.ResourceType != resource.Type)
              throw new XpediteException(String.Format(ExceptionMessages.InconsistantResourceFound, definition.ReferenceName, definition.ResourceType));

            segments.Add(EnsureBytesEncodedCorrectly(resource, encoding));
            segments.Add(newlineBytes);

            lastWriteTime = resource.LastModified < lastWriteTime ? resource.LastModified : lastWriteTime;
          }

          return new Resource
            {
              Bytes = CombineSegements(segments),
              LastModified = lastWriteTime,
              Type = definition.ResourceType,
              Encoding = encoding,
              Compressable = true
            };
        });
    }

    private static Encoding GetCompositeResourceEncoding(IEnumerable<IResource> resources)
    {
      Encoding normalizedEncoding = Encoding.UTF8;

      foreach (var resource in resources)
      {
        if (resource.Encoding.IsBrowserDisplay && _rankedEncodings[resource.Encoding] <= _rankedEncodings[normalizedEncoding])
          continue;

        normalizedEncoding = resource.Encoding;
      }

      return normalizedEncoding;
    }

    private static Byte[] EnsureBytesEncodedCorrectly(IResource resource, Encoding encoding)
    {
      return String.Compare(resource.Encoding.WebName, encoding.WebName, StringComparison.OrdinalIgnoreCase) != 0
             ? Encoding.Convert(resource.Encoding, encoding, resource.Bytes)
             : resource.Bytes;
    }

    private static Byte[] CombineSegements(IEnumerable<Byte[]> segments)
    {
      Byte[] combinedBytes = new Byte[segments.Select(item => item.Length).Sum()];
      Int32 offset = 0;

      foreach (var segment in segments)
      {
        Buffer.BlockCopy(segment, 0, combinedBytes, offset, segment.Length);
        offset += segment.Length;
      }

      return combinedBytes;
    }
  }
}
